package com.movieknight;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

import com.github.savvasdalkitsis.jtmdb.Movie;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

// HomeActivity is a blank template file for the Home tab.

public class HomeActivity extends Activity {
	private static final String LOG_TAG = TMDBMovieDownloader.class.getSimpleName();
	Socket server = null;
	TextView errorCode = null;
	Context context;
	String SessionID;
	Intent theIntent;
	
	public ArrayList<String> namesToIDs(ArrayList<String> users) throws IOException, JSONException {
		ArrayList<String> IDs = new ArrayList<String>();
		
		for(int i = 0; i < users.size(); i++) {
            try {
            	PrintWriter out = null;
				out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(server.getOutputStream())), true);
				out.println("{\"module\": \"movies\", \"method\": \"get_user_id\", \"params\": {\"username\": \"" + users.get(i) + "\"}}");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			
	        BufferedReader input;
	        input = new BufferedReader(new InputStreamReader(server.getInputStream()));
	        String ID = input.readLine();
	        IDs.add(ID);
		}

		return IDs;
	}
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
		context = getApplicationContext();
		SessionID = ((MovieKnightApp) this.getApplication()).getSessionID();
        theIntent = new Intent(this, RecommendListActivity.class);
        
        try {			
			if(server == null) {
				server = new Socket("nss324-39.cse.tamu.edu",50001);
			}
			
			if(server!=null) {
	    		((MovieKnightApp) this.getApplication()).setServer(server);
			}
			
			((MovieKnightApp) this.getApplication()).getServer();
            
    		/*//read line(s)
	        BufferedReader input;
	        input = new BufferedReader(new InputStreamReader(server.getInputStream()));
	        
	        String st = input.readLine();
			Log.v(LOG_TAG, "st: " + st);
			JSONObject jsonObject = new JSONObject(st);
			
			/*if(jsonObject.has("rating") && jsonObject.getInt("error_code") == 0) {
				movieRating = jsonObject.getString("rating");
				Log.v(LOG_TAG, "movieRating: " + movieRating);
				try {
				    rating = Integer.parseInt(movieRating);
				}
				catch(NumberFormatException nfe) {
					Log.w(LOG_TAG, "Conversion Error");
				}
			}*/
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		/*catch (JSONException e) {
			e.printStackTrace();
		}*/
        
        Button button = (Button)findViewById(R.id.requestButton);
    
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				String FILENAME = "group";
				FileInputStream fis;
				ArrayList<String> users = new ArrayList<String>();
				try {
					fis = openFileInput(FILENAME);
					InputStreamReader in = new InputStreamReader(fis);
					BufferedReader br = new BufferedReader(in);
					String data = br.readLine();
					while(data != null) {
						users.add(data);
						data = br.readLine();
					}
					fis.close();
				} catch (FileNotFoundException e2) {
					Log.v(LOG_TAG, "File Not Found");
				} catch (IOException e) {
					Log.v(LOG_TAG, "IOException");
				}

				Log.v(LOG_TAG, "users.size(): " + users.size());
				for(int i = 0; i < users.size(); i++) {
					Log.v(LOG_TAG, "user: " + users.get(i));
				}
				
				String IDString = "";
				String output = null;
				
				try {
					ArrayList<String> IDs = namesToIDs(users);
					Log.v(LOG_TAG, "IDs.size(): " + IDs.size());
					if(IDs.size() == 1) {
						IDString = IDs.get(0);
					}
					else {
						for(int i = 0; i < IDs.size(); i++) {
							Log.v(LOG_TAG, "IDs: " + IDs.get(i));
							if(i != IDs.size()-1) {
								IDString += IDs.get(i).toString() + ", ";
							}
							else if(i == 0) {
								IDString = IDs.get(i).toString() + ", ";
							}
							else {
								IDString = IDString + IDs.get(i).toString();
							}
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
	            try {
	            	PrintWriter out = null;
					out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(server.getOutputStream())), true);
					output = "{\"module\": \"recommendation\", \"method\": \"get_recommendation\", \"session_id\": \"" + SessionID + "\", \"params\": {\"friends\": [" + IDString + "]}}";
					Log.v(LOG_TAG, output);
					out.println(output);
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				
		        BufferedReader input;
		        String st = null;
		        try {
					input = new BufferedReader(new InputStreamReader(server.getInputStream()));
			        st = input.readLine();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
		        Log.v(LOG_TAG, st);
		        
		        JSONObject jsonObject = null;

				try {
					jsonObject = new JSONObject(st);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				JSONArray ranks = new JSONArray();
				ArrayList<String> theRanks = new ArrayList<String>();
				
				try {
					ranks = jsonObject.getJSONArray("est_ratings");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				for(int i = 0; i < ranks.length(); i++) {
					try {
						theRanks.add(ranks.get(i).toString());
						Log.v(LOG_TAG, theRanks.get(i));
						
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				
				JSONArray IMDBIDs = new JSONArray();
				ArrayList<String> theIMDBIDs = new ArrayList<String>();
				
				try {
					IMDBIDs = jsonObject.getJSONArray("movies");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				for(int i = 0; i < IMDBIDs.length(); i++) {
					try {
						theIMDBIDs.add(IMDBIDs.get(i).toString());
						Log.v(LOG_TAG, theIMDBIDs.get(i));
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				
		        theIntent.putStringArrayListExtra("ranks", theRanks);
		        theIntent.putStringArrayListExtra("IDs", theIMDBIDs);
		        startActivity(theIntent);

			}
		});
    }
}